package Solution_3;

import Demo_work.test3;

//求两个结点最近的公共祖先
/*
    三种情况：1、两个结点里面有一个是root结点 这样子祖先就是root
            2、两个结点分布在root的两边 这样子祖先就是root
            3、两个结点在root的同一边 祖先是两个结点的交汇点
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }
}
public class Solution {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }
        //1、其中一个就是root
        if(p == root || q == root) {
            return root;
        }
        //2、分布在两边
        TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
        TreeNode rightTree = lowestCommonAncestor(root.right,p,q);
        if(leftTree != null && rightTree != null) {
            return root;
        }
        if(leftTree != null) {
            return leftTree;
        } else {
            return rightTree;
        }
    }
}
